package com.ericsson.enap.modules.ebmLog.service.impl;

import com.ericsson.common.pojo.FTPInfoVO;
import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.ebmLog.entity.EbmEventVO;
import com.ericsson.enap.modules.ebmLog.mapper.EbmLogMapper;
import com.ericsson.enap.modules.ebmLog.service.EbmLogService;
import com.ericsson.enap.modules.ebmLog.task.EbmDownLoadTask;
import com.ericsson.enap.modules.ebmLog.task.EbmExecuteScriptTask;
import com.ericsson.enap.modules.ebmLog.task.EbmStatisticAndLoadTask;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.sys.entity.EnipNetelement;
import com.ericsson.enap.modules.sys.service.EpcDictService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @description: ebmLogServerImpl实现类
 * @author: wangjingshi
 * @create: 2021-04-19 09:57
 */
@Service
public class EbmLogServiceImpl implements EbmLogService {

    private Logger log = LoggerUtils.Logger(LogFileName.EbmLogJob);
    private final static String AMF = "AMF";
    private final static String DELAY = "EbmLogDelay";
    private final static String EbmLogDays = "EbmLogDays";


    @Autowired
    private EbmLogMapper ebmLogMapper;
    @Autowired
    private EpcDictService epcDictService;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Map<String, EbmEventVO> eventMap(Integer netType) {
        return ebmLogMapper.eventMap(netType);
    }

    /**
     *
     * @param bizType 业务代码: 3是ebmLog解析业务
     * @param collectorIp 采集器ip地址
     * @param ebmPath ebm功能业务基础路径
     * @return 该服务器所采集的网元集合
     */
    @Override
    public List<EnipNetelement> DownLoadEbmFiles(Integer bizType, String collectorIp, String ebmPath) {
        //1.查询当前采集器配置了哪些网元需要进行下载
        log.info("======= bizType:"+bizType+" ======= collectorIp:"+collectorIp);
        List<EnipNetelement> list = ebmLogMapper.queryNetelementList(bizType,collectorIp);
        log.info("======= EnipNetelement list:"+list.size());
        CountDownLatch latch = new CountDownLatch(list.size());
        Integer delay = Integer.valueOf(epcDictService.selectEpcDict(new EpcDict(DELAY)).getKeyValue());
        //2.多线程处理下载的网元，最后通过线程计数器的方式保证所有网元ebm文件下载完成后进行解析
        FTPInfoVO fTPInfoVO;
        for(int i = 0;i<list.size();i++){
            fTPInfoVO = new FTPInfoVO();
            fTPInfoVO.setHost(list.get(i).getIp4());
            fTPInfoVO.setPort(21);
            fTPInfoVO.setUserName(list.get(i).getUsername());
            fTPInfoVO.setPassword(list.get(i).getPassword());
            fTPInfoVO.setNetElementID(list.get(i).getId());
            String remotePath = ebmPath + AMF + File.separator + list.get(i).getName() + File.separator;
            String localPath = ebmPath + list.get(i).getId() + File.separator;
            EbmDownLoadTask ebmDownLoadTask = new EbmDownLoadTask(fTPInfoVO,remotePath,localPath,latch,delay);
            Thread t = new Thread(ebmDownLoadTask);
            t.start();
        }
        try {
            latch.await();
            log.info("===== All netelements download ebm files end! =====");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * 执行世凯脚本，解析ebm文件
     * @param list
     * @param eventMap
     */
    @Override
    public void AnalysisEbmFiles(List<EnipNetelement> list, Map<String, EbmEventVO> eventMap, String ebmPath) {
        CountDownLatch latch = new CountDownLatch(list.size());
        for(int i=0;i<list.size();i++) {
            String localPath = ebmPath + list.get(i).getId() + File.separator;
            EbmExecuteScriptTask ebmService = new EbmExecuteScriptTask(String.valueOf(list.get(i).getId()),localPath,latch,eventMap,ebmPath);
            Thread t = new Thread(ebmService);
            t.start();
        }
        try {
            latch.await();
            log.info("===== All netelements Analysis ebm files end! =====");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除过期文档
     * @param eventMap
     */
    @Override
    public void dropExpireDocuments(Map<String, EbmEventVO> eventMap) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            Integer delay = Integer.valueOf(epcDictService.selectEpcDict(new EpcDict(DELAY)).getKeyValue());
            String dateTime = DateUtils.getEbmLogStartMinDateTime(15+delay);
            System.out.println("=======delay:"+delay+" =======dateTime:"+dateTime);
            date = sdf.parse(dateTime.substring(0, 10));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer ebmLogDays = Integer.valueOf(epcDictService.selectEpcDict(new EpcDict(EbmLogDays)).getKeyValue());
        String cleanDate = DateUtils.beforNumDay(date, -ebmLogDays).replaceAll("-", "_");
        for(Map.Entry<String, EbmEventVO> entry:eventMap.entrySet()) {
            String name = entry.getValue().getEventName();
            String dropTable = cleanDate + "_" +name+"_ebmlog_statistics;";
            String dropQueryTable = cleanDate + "_" +name+"_query_statistics;";
            if(mongoTemplate.collectionExists(dropTable)) {
                mongoTemplate.dropCollection(dropTable);
            }
            if(mongoTemplate.collectionExists(dropQueryTable)) {
                mongoTemplate.dropCollection(dropQueryTable);
            }
        }
    }

    /**
     * 统计文件，最后把结果录入数据库
     * @param list
     * @param eventMap
     */
    @Override
    public void statisticAndLoadEbmLogs(List<EnipNetelement> list, Map<String, EbmEventVO> eventMap, String ebmPath) {
        CountDownLatch latch = new CountDownLatch(list.size());
        for(int i=0;i<list.size();i++) {
            String localPath = ebmPath + list.get(i).getId() + File.separator;
            Integer delay = Integer.valueOf(epcDictService.selectEpcDict(new EpcDict(DELAY)).getKeyValue());
            String dateTime = DateUtils.getEbmLogStartMinDateTime(15+delay);
            EbmStatisticAndLoadTask task = new EbmStatisticAndLoadTask(String.valueOf(list.get(i).getId()),localPath,latch,dateTime,eventMap,mongoTemplate);
            Thread t = new Thread(task);
            t.start();
        }
        try {
            latch.await();
            log.info("===== All netelements StatisticsAndLoadEBMFiles ebm files end! =====");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
